/**
 * 菜单, 动态路由转化
 * Created by Janus on 18/11/19.
 */

import router from './router'
import { dynamicRouters } from './router'
import { menusTreeToList, menusListToMap } from '@/utils/menusUtil'
import store from './store'
import Layout from '@/views/layout/layout'

import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式

const whiteList = ['/login'] // 不重定向白名单

const menusToRouter = (menus) => {
  const routes = []
  const menusMap = menusListToMap(menusTreeToList(menus))
  for (let i = 0; i < dynamicRouters.length; i++) {
    const route = dynamicRouters[i]
    if (menusMap[route.name]) {
      route.meta = menusMap[route.name]
      routes.push(route)
    }
  }
  return routes
}

router.beforeEach((to, from, next) => {
  NProgress.start()

  // step 1: 白名单
  if (whiteList.indexOf(to.path) !== -1) {
    next()
    return
  }

  // step 2: 检查token
  if (!getToken()) {
    localStorage.setItem('routerQuery', JSON.stringify(to.query))
    // next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    next(`/login`) // 否则全部重定向到登录页
    NProgress.done()
    return
  }

  // step 4: 检查用户信息
  if (store.getters.userLoaded) {
    // 更新当前路由状态
    store.dispatch('RefreshCurMenu', to)
    next()
    return
  }

  store.dispatch('GetInfo').then(res => {
    const menus = res.data.menus
    // 刷新用户菜单
    store.dispatch('ReloadMenus', menus)

    // 挂载异步路由
    const childRouters = menusToRouter(menus)
    if (childRouters.length) {
      const first = { path: '/', component: Layout, redirect: childRouters[0].path, name: 'home', hidden: true }
      const asyncRouters = [
        first,
        { path: '/', component: Layout, name: 'layout', hidden: false, children: childRouters },
        { path: '*', name: 'all', redirect: '/404', hidden: true }
      ]
      router.addRoutes(asyncRouters)
    }

    if (!to.name) {
      // 异步路由
      const curRouter = router.match(to.fullPath)
      if (curRouter.name && curRouter.name !== '404') {
        next({ ...curRouter })
      } else {
        next('/404')
      }
      NProgress.done()
    } else {
      next()
    }
  }).catch((err) => {
    store.dispatch('FedLogOut').then(() => {
      next({ path: '/' })
    })
  })
})

router.afterEach(() => {
  // 挂载异步路由
  NProgress.done()
})
